<template>
  <div class="home">
    <el-tabs style="height:10vh;" editable v-model="tableTabsValue" type="card" closable @tab-remove="handleTabsEdit">
      <el-tab-pane
        :key="item.name"
        v-for="(item, index) in tableTabs"
        :label="item.title"
        :name="item.name"
      >
        <span slot="label">
        <!-- <i class="el-icon-loading" style="color:red;" v-if="item.status == 1">
        <i class="el-icon-error" v-if="item.status == 2">
         contenteditable="true"
        <i class="el-icon-success" v-if="item.status == 3"> -->
        {{item.title}}
        </span>
        <div class="contailer" :style="'font-size:' + environment.fontSize + 'px;'" ref="contailer" @click="contailerClick($event, index)">
            <div v-html="item.redony">
            
            </div>
            <input v-if="environment.mode === 'NORMAL'" ref="input" v-model="item.content" @click="inputClick($event, index)" @focus="focus($event, index)" @keydown="keydown($event, index)" @keyup="keyup($event, index)" @input="inputCommand($event, index)" />
        </div>
        <div v-if="environment.mode === 'PRIVATE'" class="private_carrier" contenteditable="true"></div>
       
        
       
      </el-tab-pane>
    </el-tabs>
    <DialogInint ref="dialog" @openSession="openSession"></DialogInint>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";
import DialogInint from "@/components/DialogInint.vue";
import { sendCommand, generateKey, kekDownEnter } from '@/service/command.js';
import { backBottom, slectionHistory } from '@/service/other.js';


export default {
    name: "HomeView",
    components: {
        HelloWorld,
        DialogInint
    },
    data() {
        return {
            tableTabsValue: '1',
            tableTabs: [],
            userId: generateKey(),
            controlStatus: false,
            environment: {fontSize:20,mode: 'normal'}
        }
    },
    computed: {
        // tableTabs(){
        //     return this.$store.getters.getTable;
        // }
    },
    mounted(){
        let ws = this.$store.getters.getWs;
        if(!ws || ws.readyState != WebSocket.OPEN){
            this.$refs.dialog.showOn();
        }
    },
    methods: {
        contailerClick(event, index){       
            let a = this.$refs.input[index];
            if(a){
                a.focus();
            }
        },  
        inputClick(event, index){
            let tab = this.tableTabs[index];
            //判断光标位置
            let doc = this.$refs.input;
            // console.log('focus', event ,doc, index, doc.length,doc[index].selectionStart);
            if(doc[index].selectionStart < tab.inputCount){
                //失去焦点
                setTimeout(()=>{
                    this.$refs.input[index].selectionStart = tab.inputCount;
                    this.$refs.input[index].selectionEnd = tab.inputCount;
                },50);
            }
        },
        focus(event, index){
            let tab = this.tableTabs[index];
            //判断光标位置
            let doc = this.$refs.input;
            // console.log('focus', event ,doc, index, doc.length,doc[index].selectionStart);
            if(doc[index].selectionStart < tab.inputCount){
                //失去焦点
                setTimeout(()=>{
                    this.$refs.input[index].selectionStart = tab.inputCount;
                    this.$refs.input[index].selectionEnd = tab.inputCount;
                },100);
            }
        },
        keydown(event, index){
            //console.log('keydown', event, this.tableTabs[index]);
            let key = event.key;
            let code = event.code;
            let tab = this.tableTabs[index];
            if(key == 'Backspace'){
                if(tab.content.length == tab.inputCount){
                    event.preventDefault();
                }
            }else if(key == 'Enter'){
                kekDownEnter(this, tab);
            }
            else if(key == 'Tab'){
                event.preventDefault();
                let command = tab.content.substring(tab.inputCount);
                command += '\\t';
                console.log('Tab', command)
                sendCommand(this, command, tab.source.sessionKey);
            }else if(key == 'Control'){
                this.controlStatus = true;
            }else if(key == 'c' || key == 'd' || key == 'x') {
                if(this.controlStatus){
                    sendCommand(this, '>>>Control+' + key + '<<<', tab.source.sessionKey, environment);
                    event.preventDefault();
                }
            }else if(key == 'ArrowUp' || key == 'ArrowDown') {
                slectionHistory(tab, this.$refs.input[index], key);
            }
        },
        keyup(event, index){
            let key = event.key;
            if(key == 'Control'){
                this.controlStatus = false;
            }
        },
        inputCommand(event, index){
            //console.log('inputCommand', event, this.tableTabs[index]);
            // this.tableTabs[index].content = event.target.innerText;
        },
        handleTabsEdit(targetName, action){
            if (action === 'add') {
                this.$refs.dialog.dialogFormVisible = true;
            }
            if (action === 'remove') {
                console.log('remove', targetName, this.tableTabs);
                let tabs = this.editableTabs;
                let activeName = this.editableTabsValue;
                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.name === targetName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                activeName = nextTab.name;
                            }
                        }
                    });
                }
            }
        },
        removeTab(targetName) {
            //console.log('targetName', targetName)
            let tabs = this.tableTabs;
            let activeName = this.tableTabsValue;
            if (activeName === targetName) {
                tabs.forEach((tab, index) => {
                if (tab.name === targetName) {
                    let nextTab = tabs[index + 1] || tabs[index - 1];
                    if (nextTab) {
                        activeName = nextTab.name;
                    }
                    }
                });
            }
        
            this.tableTabsValue = activeName;
            this.tableTabs = tabs.filter(tab => tab.name !== targetName);
        },
        openSession(data){
            data.sessionKey = generateKey() + '';
            let obj = {}
            // console.log('obj=', obj, this.tableTabsValue,this.tableTabs, data);
            obj.source = data;
            obj.title = data.name;
            obj.name = (this.tableTabs.length + 1) + '';
            obj.redony = '<div>Connecting to 0' + data.host + '... at ' + (new Date()).toString() + '</div>';
            obj.inputCount = 0;
            obj.status = 1;
            obj.historyCommand = [];
            obj.historyCommandPoint = -1;
            this.tableTabs.push(obj);
            this.tableTabsValue = this.tableTabs.length + '';
            // console.log('openSession', this.$store.getters.getTable)
            var ws = this.$store.getters.getWs;
            if(ws == null || ws.readyState != WebSocket.OPEN){
                ws = new WebSocket('ws://127.0.0.1:7520');
                ws.onopen = () => {
                    this.$store.commit('setWs', ws);
                    if(ws.readyState == WebSocket.OPEN){
                        this.$refs.dialog.dialogFormVisible = false;  
                        console.log('WebSocket 连接成功', ws);
                    }
                    let linkData = {type:1, content: data,environment: this.environment}; 
                    ws.send(JSON.stringify(linkData));
                }
                ws.onmessage = (message) => {
                    console.log('onmessage:', message);
                    let data = JSON.parse(message.data);
                    let key = data.key;
                    let insertStr = data.insertStr || '';
                    for(let i in this.tableTabs){
                        if(this.tableTabs[i].source.sessionKey == key){
                            this.tableTabs[i].content = (insertStr + '  ');
                            this.tableTabs[i].inputCount = (insertStr.length + 2);
                            this.environment.mode = data.mode;
                            if(data.clear){
                                this.tableTabs[i].redony = ''
                            }
                            this.tableTabs[i].redony += data.msg;//processMsg(data.msg);                        }
                            backBottom(this);
                            
                            return;
                        }
                    }

                }
                ws.onerror = (error) => {
                    ws = null;
                    console.log('onerror', error);
                    this.$message.error('链接失败,请检查网络');
                }
                ws.onclose = () => {
                    ws = null;
                    console.log('onclose');
                    this.$store.commit('setWs', null);
                }
            }

        }
    }
};
</script>
<style lang="scss">
.add{
  display: block;
}
@keyframes blink {
    0% {
        opacity: 1; /* 完全不透明 */
    }
    50% {
        opacity: 0; /* 完全透明 */
    }
    100% {
        opacity: 1; /* 再次变为不透明 */
    }
}
.contailer{
    width: calc(100vw - 10px);
    height: 90vh;
    overflow-y: scroll;
    background-color: black;
    color: rgb(255, 255, 255);
    text-align: left;
    caret-color: rgb(255, 255, 255);
    word-wrap: break-word;
    white-space: pre-line;
    div{
        margin: 0px;
        div{
            margin: 0px;
            font-family: Simsun,sans-serif;
            border: none;
            span{
                border: none;
            }
        }
    }
    input{
        margin: 5px;
        width: calc(100% - 10px);
        background-color: black;
        color: rgb(255, 255, 255);
        border: none;
        font-size: 20px;
        outline: none;
    }
}
.private_carrier{
    width: 100vh;
    min-height: 200px;
}
</style>